package com.wm.blog_admin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;

/**
 * @author ：wm_yu
 * @description : 发送邮件类
 * @createTime ：2020/5/1
 */
@Service
public class SendEmailService {

    @Autowired(required = false)
    private  JavaMailSender javaMailSender;


    @Autowired
    private  TemplateEngine templateEngine;

    /**
     * 功能描述：发送html邮件
     *
     * @param to      发送目标邮箱
     * @param subject 邮件标题
     * @param htmlName htmlName 需要读取的html文件的文件名,不传入后缀
     */
    public void sendHtmlMail(List<String> to,String from,String subject, String htmlName, Map<String,Object> paramsMap) throws MessagingException {
        Context context = new Context();
        String userName = null;
        //设置变量
        if(!CollectionUtils.isEmpty(paramsMap)){
           paramsMap.forEach((k,v) -> {
            //设置参数
            context.setVariable(k, v);
           });
            userName = (String) paramsMap.getOrDefault("userName",null);
        }
        //html的文件名
        String tempContext = templateEngine.process(htmlName, context);
        //创建message
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //发件人
        helper.setFrom(from);
        String[] arr = new String[to.size()];
        //收件人
        helper.setTo(to.toArray(arr));
        //邮件标题
        helper.setSubject(String.format(subject,userName));
        //true指的是html邮件
        helper.setText(tempContext, true);
        //发送邮件
        javaMailSender.send(message);
    }

    public void sendSimpleMail(List<String> to, String from,String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        String[] arr = new String[to.size()];
        message.setTo(to.toArray(arr));//收信人
        message.setSubject(subject);//主题
        message.setText(content);//内容
        message.setFrom(from);//发信人
        javaMailSender.send(message);
    }


}
